package com.xkw.autocode.jdbc.mysql;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

import org.apache.commons.lang3.StringUtils;

import com.xkw.autocode.jdbc.SqlParser;
import com.xkw.autocode.jdbc.entity.ColumnEntity;
import com.xkw.autocode.jdbc.entity.TableEntity;

/**
 * 解析对应的sql语句
 * 
 * @author xiangkaiwei
 *
 */
public class MysqlSqlParser implements SqlParser{

	static final String KEY = "CREATE TABLE ";

	static final String KEY_COMMENT = "COMMENT";

	@Override
	public List<TableEntity> getTableFromSql(String sql, String tableNames) {

		List<TableEntity> tables = getTableFromSql(sql);

		if (StringUtils.isEmpty(tableNames) || tables.isEmpty()) {
			return tables;
		}

		List<TableEntity> result = new ArrayList<>();
		List<String> tabbleNameList = Arrays.asList(tableNames.split(","));
		for (TableEntity table : tables) {
			if (tabbleNameList.contains(table.getTableName())) {
				result.add(table);
			}
		}
		return result;
	}

	@Override
	public List<TableEntity> getTableFromSql(String sql) {
		List<TableEntity> tables = new ArrayList<>();

		int start = sql.indexOf(KEY);

		while ((start = sql.indexOf(KEY, start)) != -1) {
			int end = sql.indexOf(';', start);
			if (end == -1) {
				break;
			}

			String oneTableSql = sql.substring(start, end);

			tables.add(getOneTable(oneTableSql));

			start = end;
		}
		return tables;
	}

	// 解析一个表格
	private TableEntity getOneTable(String sql) {

		TableEntity table = new TableEntity();
		table.setTableName(getTableName(sql));
		table.setComments(getTableComment(sql));
		table.setColumns(getColumns(sql));
		return table;
	}

	// 获取表名
	private static String getTableName(String sql) {
		String tableName = sql.substring(sql.indexOf(KEY) + KEY.length(), sql.indexOf('('));

		tableName = tableName.replaceAll("`", "");

		return tableName.trim().toUpperCase();
	}

	// 获取表注释
	private static String getTableComment(String sql) {
		int i = sql.lastIndexOf(')');

		String comment = sql.substring(sql.indexOf(KEY_COMMENT, i) + KEY_COMMENT.length());

		comment = comment.replaceAll("`", "").replaceAll("'", "").replaceAll("=", "");

		return comment.trim();
	}

	// 获取字段
	private static List<ColumnEntity> getColumns(String sql) {
		String columnStr = sql.substring(sql.indexOf('(') + 1, sql.lastIndexOf(')'));

		columnStr = columnStr.trim();

		String[] columns = columnStr.split("\n");

		List<ColumnEntity> list = new ArrayList<>();

		for (String s : columns) {
			ColumnEntity column = getColumn(s);
			if (column != null) {
				list.add(column);
			}
		}

		return list;
	}

	private static ColumnEntity getColumn(String sql) {
		sql = sql.trim();
		String upSql = sql.toUpperCase();
		if (upSql.startsWith("PRIMARY KEY ") || upSql.startsWith("UNIQUE ") || upSql.startsWith("KEY ")
				|| upSql.startsWith("INDEX ")) {
			return null;
		}

		sql = sql.replaceAll("  ", " ");

		String[] array = sql.split(" ");

		// 字段名
		String columnName = array[0];
		columnName = columnName.replaceAll("`", "");

		// 字段类型
		String jdbcType = array[1].toUpperCase();

		// 字段注释
		String columnComment = "";

		String commentKey = KEY_COMMENT + " ";
		if (upSql.indexOf(commentKey) != -1) {
			columnComment = upSql.substring(upSql.indexOf(commentKey) + commentKey.length());
			columnComment = columnComment.replaceAll("`", "").replaceAll("'", "").replaceAll(",", "");
			columnComment = columnComment.trim();
		}

		return new ColumnEntity(columnName, jdbcType, columnComment);
	}
}
